<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="名称" prop="ruleName">
        <el-input v-model="queryParams.ruleName" placeholder="请输入名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <!-- <el-form-item label="分数" prop="score">
                <el-input v-model="queryParams.score" placeholder="请输入分数" clearable @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="赠送方式" prop="presenter">
                <el-select clearable v-model="queryParams.presenter" @keyup.enter.native="handleQuery"
                    placeholder="请选择赠送方式">
                    <el-option label="赠送" :value="1" />
                    <el-option label="不赠送" :value="2" />
                </el-select>
            </el-form-item>
            <el-form-item label="优惠券编号" prop="ticketId" label-width="90px">
                <el-select clearable v-model="queryParams.ticketId" @keyup.enter.native="handleQuery"
                    placeholder="请选择优惠券">
                    <el-option v-for="item in presenterArr" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
            </el-form-item>
            <el-form-item label="优惠券数量" prop="number" label-width="90px">
                <el-input v-model="queryParams.number" placeholder="请输入优惠券数量" clearable
                    @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="是否启用" prop="ifStart">
                <el-select clearable v-model="queryParams.ifStart" @keyup.enter.native="handleQuery"
                    placeholder="请选择是否启用">
                    <el-option label="启用" value="1" />
                    <el-option label="不启用" value="2" />
                </el-select>
            </el-form-item>
            <el-form-item label="创建人" prop="createUser">
                <el-input v-model="queryParams.createUser" placeholder="请输入创建人" clearable
                    @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="修改人" prop="updateUser">
                <el-input v-model="queryParams.updateUser" placeholder="请输入修改人" clearable
                    @keyup.enter.native="handleQuery" />
            </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['system:rule:add']">新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:rule:edit']"
          >修改</el-button
        >
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['system:rule:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['system:rule:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="ruleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="id" />
      <el-table-column label="规则名称" align="center" prop="ruleName" />
      <el-table-column label="分数" align="center" prop="score" />
      <el-table-column label="赠送方式" align="center" prop="presenter">
        <template slot-scope="scope">
          <span>{{ scope.row.presenter == 1 ? "赠送" : "不赠送" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="优惠券" align="center" prop="ticketId" width="150">
        <template slot-scope="scope">
          <span>{{ findName(scope.row.ticketId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="优惠券数量" align="center" prop="number" />
      <el-table-column label="是否启用" align="center" prop="ifStart">
        <template slot-scope="scope">
          <span>{{ scope.row.ifStart == 1 ? "启用" : "不启用" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="createUser" />
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <el-table-column label="修改人" align="center" prop="updateUser" />
      <el-table-column label="修改时间" align="center" prop="updateTime" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['system:rule:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['system:rule:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 新增或修改规则对话框 -->
    <el-dialog :title="title" :visible.sync="open" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="名称" prop="ruleName">
          <el-input style="width: 300px;" v-model="form.ruleName" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="分数" prop="score">
          <el-input v-model="form.score" style="width: 300px;" placeholder="请输入分数" />
        </el-form-item>
        <div style="width: 100%; display: flex" v-for="(item, i) in form.zyEvaluationRuleItemDtos" :key="i">
          <el-form-item label="评价内容" :prop="`zyEvaluationRuleItemDtos[${i}].evaluateProblem`" :rules="[
            {
              required: true,
              message: '请输入评价内容',
              trigger: 'change',
            },
          ]">
            <el-input v-model="item.evaluateProblem" placeholder="请输入内容" />
          </el-form-item>
          <div>
            <i style="
                  cursor: pointer;
                  margin-left: 6px;
                  margin-top: 5px;
                  font-size: 20px;
                " v-if="form.zyEvaluationRuleItemDtos.length > 1" class="el-icon-remove-outline" @click="del(i)"></i>
            <i style="
                  cursor: pointer;
                  margin-left: 6px;
                  margin-top: 5px;
                  font-size: 20px;
                " v-if="form.zyEvaluationRuleItemDtos.length < 5" class="el-icon-circle-plus-outline" @click="add"></i>
          </div>
        </div>
        <el-form-item label="赠送方式" prop="presenter">
          <el-select style="width: 210px" clearable v-model="form.presenter" placeholder="请选择赠送方式">
            <el-option label="赠送" :value="1" />
            <el-option label="不赠送" :value="2" />
          </el-select>
        </el-form-item>
        <div v-if="form.presenter == 1">
          <el-form-item label="优惠券编号" prop="ticketId">
            <el-select clearable v-model="form.ticketId" style="width: 300px;" placeholder="请选择优惠券">
              <el-option v-for="item in presenterArr" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="优惠券数量" prop="number">
            <el-input v-model="form.number" style="width: 300px;" placeholder="请输入优惠券数量" />
          </el-form-item>
        </div>
        <!-- <el-row>
                    <el-col :span="12">
                        <el-form-item label="创建人" prop="createUser">
                            <el-input v-model="form.createUser" placeholder="请输入创建人" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="修改人" prop="updateUser">
                            <el-input v-model="form.updateUser" placeholder="请输入修改人" />
                        </el-form-item>
                    </el-col>
                </el-row> -->
        <el-row>
          <el-col :span="14">
            <el-form-item label="获取评价数量" prop="scopeNum">
              <el-input v-model="form.scopeNum"  style="width: 300px;" placeholder="获取最近N条计算综合评分" />
            </el-form-item>
          </el-col>
          <el-col :span="14">
            <el-form-item label="默认完成天数" prop="autoComplete">
              <el-input v-model="form.autoComplete"  style="width: 300px;" placeholder="订单N天'未完成'评价转为'已完成'" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="是否启用" prop="ifStart">
          <el-radio-group v-model="form.ifStart">
            <el-radio label="1">启用</el-radio>
            <el-radio label="2">不启用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listRule,
  getRule,
  delRule,
  addRule,
  updateRule,
  getPresenterList,
} from "@/api/system/rule/rule";
import { fetchRegionList, fetchStoreList } from "@/api/system/orderList/order";
export default {
  name: "Rule",
  data() {
    return {
      itemBeforeRuleList: [{ index: 0 }],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 【请填写功能名称】表格数据
      ruleList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        ruleName: null,
        score: null,
        presenter: null,
        ticketId: null,
        number: null,
        ifStart: null,
        createUser: null,
        updateUser: null,
      },
      // 表单参数
      form: {
        zyEvaluationRuleItemDtos: [{ evaluateProblem: "" }],
      },
      // 表单校验
      rules: {
        ruleName: [{ required: true, message: "请输入名称", trigger: "blur" }],
        score: [
          { required: true, message: "请输入评分", trigger: "blur" },
          {
            pattern: /^([1-5](\.\d+)?|0(\.\d+)?)$/,
            message: "请输入大于等于1小于等于5的数字",
            trigger: "blur",
          },
        ],
        presenter: [
          {
            required: true,
            message: "请选择赠送方式",
            trigger: ["blur", "change"],
          },
        ],
        ticketId: [
          {
            required: true,
            message: "请选择优惠券",
            trigger: ["blur", "change"],
          },
        ],
        number: [
          { required: true, message: "请输入优惠券数量", trigger: "blur" },
        ],
        scopeNum: [
          { required: true, message: "请输入获取评价数量", trigger: "blur" },
        ],
        autoComplete: [
          { required: true, message: "请输入默认完成天数", trigger: "blur" },
        ],
        ifStart: [
          { required: true, message: "请选择是否启用", trigger: "change" },
        ],
      },
      itemBeforeRuleNumber: 0,
      presenterArr: [],
      regionOption: [], // 区域下拉框
      storeOption: [], // 门店下拉框
      // searchStoreOption: [],
    };
  },
  created() {
    this.getList();
    this.GetPresenterArr();
    this.getRegionOption();
  },
  methods: {
    findName(item) {
      const aa = this.presenterArr.find((el) => el.id == item);
      if (aa) {
        return aa.name;
      }
    },
    GetPresenterArr() {
      getPresenterList().then((res) => {
        console.log(res.rows);
        this.presenterArr = res.rows;
      });
    },
    //添加评价内容
    add() {
      this.form.zyEvaluationRuleItemDtos.push({ evaluateProblem: "" });
    },
    //删除评价内容
    del(i) {
      this.form.zyEvaluationRuleItemDtos.splice(i, 1);
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      listRule(this.queryParams).then((response) => {
        this.ruleList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        score: null,
        presenter: null,
        ticketId: null,
        number: null,
        ifStart: null,
        createTime: null,
        zyEvaluationRuleItemDtos: [{ evaluateProblem: "" }],
        updateTime: null,
        scopeNum: null,
        autoComplete: null,
        // updateUser: null
      };
      this.itemBeforeRuleList = [{ index: 0 }];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新增规则";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;

      getRule(id).then((response) => {
        const data = Object.keys(response.data)
          .filter((key) => !key.includes("zyEvaluationRuleItemVos"))
          .reduce((acc, key) => {
            acc[key] = response.data[key];
            return acc;
          }, {});
        this.form = {
          ...data,
          zyEvaluationRuleItemDtos: response.data.zyEvaluationRuleItemVos,
        };
        this.open = true;
        this.title = "修改规则";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          console.log(this.form, "this.form");
          if (this.form.id != null) {
            updateRule(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addRule(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除规则编号为"' + ids + '"的数据项？')
        .then(function () {
          return delRule(ids);
        })
        .then((res) => {
          if (res.code) {
            this.getList();
            this.$modal.msgSuccess("删除成功");
          }
        })
        .catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/evaluate/rule/export",
        {
          ...this.queryParams,
        },
        `rule_${new Date().getTime()}.xlsx`
      );
    },
    // 获取归属区域下拉数据
    getRegionOption() {
      fetchRegionList().then((res) => {
        this.regionOption = res.data.map((rItem) => {
          return {
            value: rItem.id,
            label: rItem.regionName,
          };
        });
      });
    },
  },
};
</script>
